//
//  XTTabBar.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/11.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

//自定义协议
protocol XTTabBarDelegate : NSObjectProtocol{
    //点击新增微博的按钮调用的闭包
    func didSelectedComposeButton()

}


class XTTabBar: UITabBar {

    //设置闭包
    var tabBarBtnClosure:(()->())?
    weak var xtDelegate : XTTabBarDelegate?
    
    //创建新增微博按钮
    //懒加载
    private lazy var composeButton:UIButton={

        let button = UIButton()
//        weak var 
        //给button添加动作
        
        button.addTarget(self, action: "tabBarBtnClick", forControlEvents: .TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
        
        
        }()
    
    //此处的含义是：该view为代码创建
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    //由上面的方法自动提示出来：表示代码创建的view，若使用了storyBoard或xib，那么就会报错，提示如下
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
                //若需要使用xib等，则执行
//    init?(coder aDecoder: NSCoder) {
//        super.init(coder: aDecoder)
//    }
    
    //添加按钮
    func setupUI(){
        addSubview(composeButton)
    
    }
    
    //设置子试图的布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        let itemW:CGFloat = frame.size.width/5
        //记录当前遍历的是第几个button
        var index = 0
        //遍历子视图
        for childView in subviews{
            if childView .isKindOfClass(NSClassFromString("UITabBarButton")!){
            childView.frame.size.width = itemW
            childView.frame.origin.x = CGFloat(index) * itemW
                
                index++
                
                if index == 2 {
                index++ //index和＋＋中间千万不能有空格！！！
                }
            }
        }
    }

    //点击方法
    @objc private func tabBarBtnClick(){
        tabBarBtnClosure?()
        xtDelegate?.didSelectedComposeButton()
        
    }
    
    
}
